﻿using System;
using System.Xml;
namespace Codemonk.Excel.Parser
{
    internal static class DelegateExtensions
    {
        public static void SafeInvoke(this Action action)
        {
            try
            {
                action();
            }
            catch { }
        }
        public static T SafeInvoke<T>(this Func<T> func, T defaultValue = default(T))
        {
            try
            {
                return func();
            }
            catch { return defaultValue; }
        }
    }
    internal static class ConverterExtensions
    {
        public static T As<T>(this string input, Func<string, T> parser, T defaultValue = default(T))
        {
            Func<T> p = () => parser(input);
            return p.SafeInvoke<T>(defaultValue);
        }
        public static string AsString(this string input, string defaultValue = "")
        {
            Func<string> p = () => input + "";
            return p.SafeInvoke<string>(defaultValue);
        }
        public static int AsInt32(this string input, int defaultValue = 0)
        {
            Func<int> p = () => int.Parse(input);
            return p.SafeInvoke<int>(defaultValue);
        }
        public static float AsFloat(this string input, float defaultValue = 0f)
        {
            Func<float> p = () => float.Parse(input);
            return p.SafeInvoke<float>(defaultValue);
        }
        public static double AsDouble(this string input, double defaultValue = 0d)
        {
            Func<double> p = () => double.Parse(input);
            return p.SafeInvoke<double>(defaultValue);
        }
        public static decimal AsDecimal(this string input, decimal defaultValue = 0m)
        {
            Func<decimal> p = () => decimal.Parse(input);
            return p.SafeInvoke<decimal>(defaultValue);
        }
    }
    internal static class XmlExtensions
    {
        public static T As<T>(this XmlNode input, string xpath, Func<string, T, T> parser, T defaultValue = default(T))
        {
            Func<T> p = () => parser(input.SelectSingleNode(xpath).Value, defaultValue);
            return p.SafeInvoke<T>(defaultValue);
        }
    }
}
